<template>
  <!--添加标题-->
  <el-card shadow="hover">
    <template #header>
      <div class="card-header">
        <el-button @click="addNewArticle" >添加新文章</el-button>
        <span class="button"></span>
      </div>
    </template>
    <div
      class="text item"
      style="cursor:pointer"
      v-for="(item, index) in dataList"
      :key="'article_' + index"
      @click="changeArticle(item.ID)"
    >
      {{item.ID}}：{{item.title}} ({{dateFormat(item.addTime).format('YYYY-MM-DD')}})
    </div>
    <el-empty description="该分类里面还没有文章呢。" v-if="dataList.length === 0"></el-empty>
    <!--分页-->
    <pager flag="articleList"/>
  </el-card>
</template>

<script setup>
import { computed, reactive, watch } from 'vue'
// 组件
import pager from '../components/pager.vue'
// model
import { blogForm } from '../model/blogModel'
// 状态
import VueDS from 'vue-data-state'
// webSQL
import { webSQLVue } from 'nf-web-storage'

// 数据列表的状态
import dataListControl from '../control/data-list'

// 日期格式化
const dateFormat = dayjs

// 列表状态管理，博文列表
const { regDataListState, dataList } = dataListControl('articleList')

// 注册状态，注入获取博文列表需要 查询条件 和 分页信息
const blogState = regDataListState()
// 获得数据
blogState.isReload = !blogState.isReload
// console.log('blogState', blogState)

// 访问状态
const { reg, get } = VueDS.useStore()
// 注册编辑博文的状态
const editBlogState = get.editBlogState()
console.log('editBlogState', editBlogState)

// 访问 webSQL
const { blog } = webSQLVue.useHelp()

// 做个转换
watch(() => editBlogState.groupId, (id) => {
  blogState.find.groupId = id
  blogState.isReload = !blogState.isReload
})

// 添加新文章，仅标题、时间
const addNewArticle = () => {
  const newArticle = blogForm()
  // 选择的分组ID
  newArticle.groupId = editBlogState.groupId
  // 用日期作为默认标题
  newArticle.title = dayjs(new Date()).format('YYYY-MM-DD')

  blog.insert(newArticle).then((id) => {
    console.log('新ID：', id)
    // 设置
    // 通知列表
    newArticle.ID = id
    dataList.unshift(newArticle)
  })
}

// 选择要编辑的文章
const changeArticle = (id) => {
  editBlogState.editBlogId = id
}

</script>

<style>
  .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
  }

  .text {
    font-size: 14px;
  }

  .item {
    padding-left: 30px;
    margin-bottom: 18px;
  }

</style>
